<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace App\Model\LazyCommon;
use App\Base\BaseModel;
use App\Entity\UserGroupsRole;
use App\Setting\LazyCommon\UserGroupsRoleSetting;

class UserGroupsRoleModel extends BaseModel{

    /*
     * 列表基本设置【通用模块必须开发】
     */
    public function listSettingDefault()
    {
        $settings = new UserGroupsRoleSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    /*
     * 为后台获取所有文章分类【通用模块必须开发】
     */
    /**
     * @param array $params $param[textKey]=textKey , $param[conditions][table][field][eq|gt|lt...]=value , $param[orderBy][table][field]=DESC|ASC
     * @param int $offset
     * @param int $perPage
     * @return array
     */
    public function getAdminLists($params ,$offset = 0 , $perPage = 10)
    {
        $qb = $this->getQueryFromParam($params);
        $lists = $this->getAllResult($qb,$offset,$perPage);
        $total = $this->countAllResult($qb);

        return array(
            "total" => $total ? $total : 0,
            "data"  => $lists
        );
    }
    /*
     * 通用Rep
     */
    public function getRep()
    {
        $settings = new UserGroupsRoleSetting($this->getDoctrine());
        return $this->em->getRepository($settings->bundleName.":".$settings->entityName);
    }

    /**
     * @param $groups
     * @return \App\Entity\UserGroupsRole[]
     */
    public function getByGroups($groups)
    {
        /**@var $list UserGroupsRole[] */
        $list = $this->getRep()->findBy(array("groups"=>$groups));
        return $list;
    }

    public function getRoles4Groups($groups)
    {
        /**@var $list UserGroupsRole[] */
        $list = $this->getByGroups($groups);
        $roles = [];
        foreach ($list as $item) {
            $roles[] = $item->getRole();
        }
        return $roles;
//        var_dump($list);
    }


    public function update($groups,$roles)
    {
        $orgList = $this->getByGroups($groups);
        foreach ($orgList as $one) {
            $this->em->remove($one);
        }
        foreach ($roles as $role) {
            $UserGroupsRole = new UserGroupsRole();
            $UserGroupsRole->setGroups($groups)->setRole($role);
            $this->em->persist($UserGroupsRole);
        }
        $this->em->flush();
    }
}